package com.zlp.spring.tx.service.v1.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * mybatis 配置
 * https://mybatis.org/spring/zh/getting-started.html
 * @date: 2022/2/21 19:52
 */
@Configuration
@MapperScan("com.zlp.spring.tx.service.v1.mapper")
@ComponentScan("com.zlp.spring.tx.service.v1")
@EnableTransactionManagement
public class MybatisConfig {


    private static final String URL ="jdbc:mysql://47.103.20.21:3307/zlp-mall?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
    private static final String DRIVER_CLASS_NAME ="com.mysql.jdbc.Driver";
    private static final String USER_NAME ="root";
    private static final String PASSWORD ="zlp123456";

    /**
     * 数据源配置
     * @date: 2022/2/22 9:21
     * @return: javax.sql.DataSource
     */
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setUrl(URL);
        driverManagerDataSource.setDriverClassName(DRIVER_CLASS_NAME);
        driverManagerDataSource.setUsername(USER_NAME);
        driverManagerDataSource.setPassword(PASSWORD);
        return driverManagerDataSource;
    }

    /**
     * 创建 SqlSessionFactory
     * @date: 2022/2/22 9:24
     * @return: org.apache.ibatis.session.SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource());
        return dataSourceTransactionManager;
    }



}